import {Component, OnInit, ViewChild} from '@angular/core';
import {Globals} from '../../globals';
import {BaseService} from '../../shared/service/base.service';
import {FormBuilder, FormGroup} from '@angular/forms';
import {PageHelper} from '../../utils/page-helper-model';
import {ApiUrl} from '../../config/api-url';
import {MyDateModel} from '../../models/my-date.model';
import {Observable} from 'rxjs';
import {Consts} from '../../config/consts';
import {RoleIdEnum} from '../../enums/role-id.enum';
import {DeviceTypeEnum} from "../../enums/device-type.enum";
import {Router} from '@angular/router';
@Component({
  selector: 'app-sale',
  templateUrl: './sale.component.html',
  styleUrls: ['./sale.component.less']
})
export class SaleComponent implements OnInit {
  isMobile = Globals.isMobile();
  // 分页
  pageHelper: PageHelper = new PageHelper;
  // 模态框表单
  formModel: FormGroup;

  listOfData: any;
  // 开始日期类型
  startDateTimeType = 'start';
  // 结束日期类型
  endDateTimeType = 'end';
  // 开始日期
  startDateTime: Date;
  // 结束日期
  endDateTime: Date;
  // 支付完成时间（开始时间）
  gmtPaymentStart: Date;
  // 支付完成时间（结束时间）
  gmtPaymentEnd: Date;
  // 门店
  merchantStoreList: [];
  isCollapse = true;
  customerServiceInfo:any;
  store: any;
  showStatistic = false;
  isVisibleBranInfo = false;
  orderStatistic: any;
  userInfo: any;
  isVisibleCommodityInfo = false;

  // 机构
  agencyList: [];
  // 运营商
  userList: [];
  // 显示模态框
  isVisible = false;
  orderRefund: any;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };
  deviceTypeEnum = {
    VENDING_MACHINE: DeviceTypeEnum.VENDING_MACHINE,
    SCREEN_VENDING_MACHINE: DeviceTypeEnum.SCREEN_VENDING_MACHINE,
    OPEN_DOOR_VENDING_MACHINE: DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE,
  };
  constructor(private baseService: BaseService,
              private fb: FormBuilder, private router: Router) {
    this.buildForm();
  }

  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.startDateTime = this.baseService.zorro.getDateTime().startToday;
    this.endDateTime = this.baseService.zorro.getDateTime().endToday;
    this.findData();
    this.findAllMerchantStoreByUserInfo();
    this.getAllUserOfName();
    this.getAllAgencyOfName();
  }

  buildForm() {
    this.formModel = this.fb.group({
      outTradeNo: [null, []],
      merchantStoreId: ['0', []],
      memberId: ['', []],
      userId: ['', []],
      status: ['-1', []],
      createTime: [null, []],
      updateTime: [null, []],
      gmtPaymentStart: [null, []],
      gmtPaymentEnd: [null, []],
      mchType: ['-1', []],
      agencyId: ['', []],
      deviceNo: [null, []],
      merchantId: [null, []],
    });
  }
  onPageSizeChange(pageSize: any){
    // console.log(pageSize, 'pageSize');
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.findData();
  }
  findData() {
    this.formModel.get('createTime').setValue(this.startDateTime);
    this.formModel.get('updateTime').setValue(this.endDateTime);
    this.formModel.get('gmtPaymentStart').setValue(this.gmtPaymentStart);
    this.formModel.get('gmtPaymentEnd').setValue(this.gmtPaymentEnd);
    this.baseService.findListByMuchCondition(ApiUrl.OrderUrl + '/list', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.listOfData = data.data.list;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  checkOutTradeNo(data){
    console.log(data,"data")
    //路由跳转
    this.router.navigateByUrl('/sell?outTradeNo=' + data.outTradeNo +
      '&merchantStoreId=' + data.merchantStoreId + '&userId=' + data.userId + '&startDateTime=' +  this.startDateTime,
      {skipLocationChange: true});
  }
  // 子组件向父组件传值
  setVisible(body) {
    this.isVisible = body.isVisible;
    this.findData();
  }
  setVisibleBranInfo(body) {
    this.isVisibleBranInfo = body.isVisibleBranInfo;
    this.findData();
  }
  setVisibleCommodityInfo(body) {
    this.isVisibleCommodityInfo = body.isVisibleCommodityInfo;
    // this.findData();
  }
  findAllMerchantStoreByUserInfo() {
    let userId = null;
    if (this.formModel.get('userId').value != null) {
      userId = this.formModel.get('userId').value;
    } else {
      userId = '';
    }
    this.baseService.get(ApiUrl.MerchantStoreUrl + '/findAllMerchantStoreByUserInfo?userId=' + userId).subscribe(
      data => {
        if (data.status == 0) {
          this.merchantStoreList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  gainAgencyId($event: any) {
    this.getAllUserOfName();
  }


  gainUserId($event: any) {
    this.findAllMerchantStoreByUserInfo();
  }


  submitForm() {
    if (this.startDateTime == null && this.endDateTime == null && this.gmtPaymentStart == null && this.gmtPaymentEnd == null){
      this.baseService.layer.messageError("下单时间、支付时间必须其中一个范围");
      return;
    }

    if (this.startDateTime != null && this.endDateTime == null){
      this.baseService.layer.messageError("必选下单结束时间");
      return;
    }

    if (this.startDateTime == null && this.endDateTime != null){
      this.baseService.layer.messageError("必选下单开始时间");
      return;
    }

    if (this.gmtPaymentStart != null && this.gmtPaymentEnd == null){
      this.baseService.layer.messageError("必选支付结束时间");
      return;
    }

    if (this.gmtPaymentStart == null && this.gmtPaymentEnd != null){
      this.baseService.layer.messageError("必选支付开始时间");
      return;
    }
    this.pageHelper.currentPage = 1;
    this.findData();
  }
  checkBranInFo(data){
    this.isVisibleBranInfo = true;
    this.store = data;
  }
  checkCommodityInFo(data){
    this.isVisibleCommodityInfo = true;
    this.store = data;
  }

  // 将开始、结束时间往外抛
  outDateTime($event: MyDateModel) {
    /**
     * date: Fri Mar 19 2021 23:59:06 GMT+0800 (中国标准时间) {}
     * type: "end"
     */
    if ($event.type == 'start') {
      this.startDateTime = $event.date;
    } else if ($event.type == 'end') {
      this.endDateTime = $event.date;
    }
  }

  gmtPaymentTime($event: MyDateModel) {
    if ($event.type == 'start') {
      this.gmtPaymentStart = $event.date;
    } else if ($event.type == 'end') {
      this.gmtPaymentEnd = $event.date;
    }
  }
  skipCoin(id: any, endDateTime: any, startDateTime: any) {
    this.router.navigateByUrl('/coin?orderId=' + id + '&endDateTime=' + endDateTime + '&startDateTime=' + startDateTime,
      {skipLocationChange: true});
  }

  skipUser(memberId: any){
    if (!memberId){
      return
    }
    this.router.navigateByUrl('/user?memberId=' + memberId,
      {skipLocationChange: true});
  }
  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.findData();
  }

  // 数据导出
  exportCsv() {
    if (this.startDateTime == null || this.endDateTime == null) {
      this.baseService.layer.messageError('请选择订单时间!');
      return null;
    }
    this.baseService.layer.modalConfirm('确定导出数据吗？', confirm => {
      if (confirm) {
        this.formModel.get('createTime').setValue(this.startDateTime);
        this.formModel.get('updateTime').setValue(this.endDateTime);
        this.baseService.post(ApiUrl.OrderUrl + '/export/list', this.formModel.value).subscribe(
          res => {
            console.log('数据导出返回值', res);
            if (res.status == 0) {
              this.export(res.data.downloadUrl, res.data.fileName);
            } else {
              this.baseService.layer.messageError(res.msg);
            }
          }
        );
      }
    });
  }


  // Blob文件转换下载
  export(url: any, fileName: string, fileType?: any) {
    this.requestBlob(url, {}).subscribe(result => {
      this.downFile(
        result,
        fileName,
        fileType ||
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
    });
  }

  downFile(result, fileName, fileType?) {
    const data = result.body;
    const blob = new Blob([data], {type: fileType || data.type});
    const objectUrl = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.setAttribute('style', 'display:none');
    a.setAttribute('href', objectUrl);
    a.setAttribute('download', fileName);
    a.click();
    URL.revokeObjectURL(objectUrl);
  }

  requestBlob(url: any, data?: any): Observable<any> {
    return this.baseService.http.request('post', url, {
      body: data,
      observe: 'response',
      responseType: 'blob',
    });
  }


  statisticQuery() {
    this.showStatistic = true;
    this.formModel.get('createTime').setValue(this.startDateTime);
    this.formModel.get('updateTime').setValue(this.endDateTime);
    this.baseService.findListByMuchCondition(ApiUrl.OrderUrl + '/findOrderStatistics', this.formModel.value, this.pageHelper).subscribe(res => {
      if (res.status == 0) {
        this.orderStatistic = res.data;
      } else {
        this.baseService.layer.messageError(res.msg);
      }
    });
  }

  getAllAgencyOfName() {
    this.baseService.get(ApiUrl.AgencyUrl + '/getAllAgencyOfName').subscribe(data => {
      if (data.status == 0) {
        this.agencyList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getAllUserOfName() {
    let agencyId = this.formModel.get('agencyId').value;
    if (agencyId == null) {
      agencyId = '0';
    }
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=' + agencyId).subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }


  pastStatistic() {
    if (this.userInfo.roleId == RoleIdEnum.SUPER_ADMINISTRATOR || this.userInfo.roleId == RoleIdEnum.AGENT) {
      this.router.navigateByUrl('/statistic/agency-statistic');
    } else {
      this.router.navigateByUrl('/statistic/user-statistic');
    }
  }

  refund(data) {
    this.isVisible = true;
    this.orderRefund = data;
  }
}
